package com.lysj.bhp.financial.util;

import com.lysj.bhp.financial.base.FinancialContent;
import com.lysj.bhp.financial.domain.Financial;
import com.lysj.bhp.financial.domain.UserEarnings;
import com.lysj.bhp.financial.domain.UserEarningsRecord;
import com.lysj.bhp.financial.domain.UserFinancialRecord;
import com.lysj.bhp.user.domain.User;
import com.lysj.bhp.user.util.MyWallet;
import com.lysj.bhp.wallet.domain.BhpcWallet;
import com.lysj.bhp.wallet.domain.BitCoinWallet;
import com.lysj.bhp.wallet.domain.EthereumWallet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Date;
import java.util.List;

@Component
public class UserEarningsTimer extends FinancialContent {

    private static Logger logger = LoggerFactory.getLogger(UserEarningsTimer.class);
    @Resource
    MyWallet myWallet;


    /**
     * @author drj
     * @date 2018/07/20 11:11
     * @Description:用户理财收益定时器
     */
    @Scheduled(cron = "00 00 00 * * ?")
    public void createUserEarnings() {
        System.out.println("---开始计算理财收益----");
        //查询出正在理财的产品
        List<Financial> financials = financialRepository.findByStatusAndIsExist(2, 1);

        financials.forEach((Financial financial) -> {
            List<UserFinancialRecord> userFinancialRecordList = userFinancialRecordRepository.findByFinancialId(financial.getFinancialId());
            for (UserFinancialRecord userFinancialRecord : userFinancialRecordList) {
                BigDecimal earningsRate = financial.getEarningsRate().divide(new BigDecimal("100"));//收益率
                BigDecimal investmentPortion = userFinancialRecord.getInvestmentPortion();//投资份额
                BigDecimal deadline = new BigDecimal(String.valueOf(financial.getDeadline()));//投资期限
                BigDecimal exchangeRate = getExchangeRate(financial.getInvestmentType(), financial.getEarningsType());//收益币种当日买入价
                //收益 = (收益率*期初本金/投资期限)*收益币种当日买入价;
                BigDecimal dividie = (earningsRate.multiply(investmentPortion).multiply(exchangeRate)).divide(deadline, 6, BigDecimal.ROUND_DOWN);//收益

                User user = userRepository.findByUserId(userFinancialRecord.getUserId());

                //创建用户收益记录
                UserEarningsRecord userEarningsRecord = new UserEarningsRecord();
                userEarningsRecord.setUserId(userFinancialRecord.getUserId());
                userEarningsRecord.setUserFinancialRecordId(userFinancialRecord.getUserFinancialRecordId());
                userEarningsRecord.setFinancialId(userFinancialRecord.getFinancialId());
                userEarningsRecord.setFinancialName(financial.getName());
                userEarningsRecord.setInvestmentPortion(userFinancialRecord.getInvestmentPortion());
                userEarningsRecord.setExchangeRate(exchangeRate);
                userEarningsRecord.setDivided(dividie);
                userEarningsRecord.setCreateDate(new Date());
                userEarningsRecord.setEmail(user.getEmail());

                logger.info(user.getUserId() + ":" + userFinancialRecord.getInvestmentPortion() + "=>" + dividie);
                //查询用户总收益表
                UserEarnings userEarnings = userEarningsRepository.findByUserId(userFinancialRecord.getUserId());
                try {
                    switch (financial.getEarningsType()) {
                        //收益类型为btc
                        case 10:
                            //增加用户的比特币总收益
                            userEarnings.setBtcEarnings(userEarnings.getBtcEarnings().add(dividie));
                            //增加该用户btc钱包可用余额跟总额
                            BitCoinWallet bitCoinWallet = bitcoinWalletRepository.findByUserId(userFinancialRecord.getUserId());
                            if (null == bitCoinWallet) {
                                bitCoinWallet = (BitCoinWallet) myWallet.createBitWallet(user.getUserId(), user.getEmail()).getObj();
                            }
                            bitCoinWallet.setAvailBalance(bitCoinWallet.getAvailBalance().add(userEarningsRecord.getDivided()));
                            bitCoinWallet.setBalance(bitCoinWallet.getBalance().add(userEarningsRecord.getDivided()));
                            bitcoinWalletRepository.save(bitCoinWallet);
                            break;
                        case 20:
                            //增加用户的以太坊总收益
                            userEarnings.setEthEarnings(userEarnings.getEthEarnings().add(userEarningsRecord.getDivided()));
                            //增加该用户eth钱包可用余额跟总额
                            EthereumWallet ethereumWallet = ethereumWalletRepository.findByUserId(userFinancialRecord.getUserId());
                            if (null == ethereumWallet) {
                                ethereumWallet = (EthereumWallet) myWallet.createEthWallet(user.getUserId()).getObj();
                            }
                            ethereumWallet.setAvailBalance(ethereumWallet.getAvailBalance().add(userEarningsRecord.getDivided()));
                            ethereumWallet.setBalance(ethereumWallet.getBalance().add(userEarningsRecord.getDivided()));
                            ethereumWalletRepository.save(ethereumWallet);
                            break;
                        case 100:
                            //增加用户的BHPC总收益
                            userEarnings.setBhpcEarnings(userEarnings.getBhpcEarnings().add(userEarningsRecord.getDivided()));
                            //增加该用户eth钱包可用余额跟总额
                            BhpcWallet bhpcWallet = bhpcWalletRepository.findByUserId(userFinancialRecord.getUserId());
                            if (null == bhpcWallet) {
                                bhpcWallet = (BhpcWallet) myWallet.createBhpcWallet(user.getUserId());
                            }
                            bhpcWallet.setAvailBalance(bhpcWallet.getAvailBalance().add(userEarningsRecord.getDivided()));
                            bhpcWallet.setBalance(bhpcWallet.getBalance().add(userEarningsRecord.getDivided()));
                            bhpcWalletRepository.save(bhpcWallet);
                            break;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //更改理财明修表的利息数量,用户理财表的数额
                userFinancialRecord.setDivide(userFinancialRecord.getDivide().add(userEarningsRecord.getDivided()).setScale(6, BigDecimal.ROUND_DOWN));
                userEarningsRepository.save(userEarnings);
                userFinancialRecordRepository.save(userFinancialRecord);
                userEarningsRecordRepository.save(userEarningsRecord);
            }
        });
        System.out.println("---理财包状态定时器任务---");
        financialScheduled();
        System.out.println("---释放用户资产---");
        releaseUserBalance();
    }


    public void financialScheduled() {
        Long time = System.currentTimeMillis();
        // 查询理财状态为1,未开始的理财
        List<Financial> financialList = financialRepository.findByStatusAndIsExist(1, 1);
        for (Financial financial : financialList) {
            //若当前时间大于起息时间
            if (time >= financial.getInterestDate().getTime()) {
                // 更改理财状态为进行中
                financial.setStatus(2);
            }
        }
        financialRepository.save(financialList);
        // 查询理财状态为2,进行中的理财
        List<Financial> conductFinancialList = financialRepository.findByStatusAndIsExist(2, 1);
        for (Financial financial : conductFinancialList) {
            //若当前时间大于理财结束时间
            if (time >= financial.getEndIntersetDate().getTime()) {
                // 更改理财状态为已结束
                financial.setStatus(3);
            }
        }
        financialRepository.save(conductFinancialList);
    }

    public void releaseUserBalance() {
        //查询出理财过期的产品
        List<Financial> overDuefinancials = financialRepository.findByStatusAndIsExist(3, 1);

        overDuefinancials.forEach((financial) -> {
            List<UserFinancialRecord> userFinancialRecordList = userFinancialRecordRepository.findByFinancialIdAndIsRelease(financial.getFinancialId(), 1);
            for (UserFinancialRecord userFinancialRecord : userFinancialRecordList) {
                switch (financial.getInvestmentType()) { //投资类型 10:BTC,20:ETH,100:BHPC
                    case 10:
                        BitCoinWallet bitCoinWallet = bitcoinWalletRepository.findByUserId(userFinancialRecord.getUserId());
                        bitCoinWallet.setAvailBalance(bitCoinWallet.getAvailBalance().add(userFinancialRecord.getInvestmentPortion()));
                        bitCoinWallet.setBalance(bitCoinWallet.getBalance().add(userFinancialRecord.getInvestmentPortion()));
                        bitcoinWalletRepository.save(bitCoinWallet);
                        break;
                    case 20:
                        EthereumWallet ethereumWallet = ethereumWalletRepository.findByUserId(userFinancialRecord.getUserId());
                        ethereumWallet.setAvailBalance(ethereumWallet.getAvailBalance().add(userFinancialRecord.getInvestmentPortion()));
                        ethereumWallet.setBalance(ethereumWallet.getBalance().add(userFinancialRecord.getInvestmentPortion()));
                        ethereumWalletRepository.save(ethereumWallet);
                        break;
                    case 100:
                        BhpcWallet bhpcWallet = bhpcWalletRepository.findByUserId(userFinancialRecord.getUserId());
                        bhpcWallet.setAvailBalance(bhpcWallet.getAvailBalance().add(userFinancialRecord.getInvestmentPortion()));
                        bhpcWallet.setBalance(bhpcWallet.getBalance().add(userFinancialRecord.getInvestmentPortion()));
                        bhpcWalletRepository.save(bhpcWallet);
                        break;
                    default:
                        break;
                }
                userFinancialRecord.setIsRelease(2);
            }
            userFinancialRecordRepository.save(userFinancialRecordList);
        });
    }


    public BigDecimal getExchangeRate(Integer investmentType, Integer earningsType) {
        BigDecimal investmentRate = new BigDecimal("1");
        BigDecimal earningsRate = new BigDecimal("1");
        BigDecimal exchangeRate = new BigDecimal("1");
        if (10 == investmentType) {
            investmentRate = exchangeRates.getBITCOIN_TO_DOLLAR();
        }
        if (20 == investmentType) {
            investmentRate = exchangeRates.getETHEREUM_TO_DOLLAR();
        }
        if (100 == investmentType) {
            investmentRate = exchangeRates.getBHPC_TO_DOLLAR();
        }
        if (10 == earningsType) {
            earningsRate = exchangeRates.getBITCOIN_TO_DOLLAR();
        }
        if (20 == earningsType) {
            earningsRate = exchangeRates.getETHEREUM_TO_DOLLAR();
        }
        if (100 == earningsType) {
            earningsRate = exchangeRates.getBHPC_TO_DOLLAR();
        }
        return exchangeRate = investmentRate.divide(earningsRate, 6, BigDecimal.ROUND_DOWN);

    }
}
